/*
 * Galaxium Messenger
 * 
 * Copyright (C) 2003 Philippe Durand <draekz@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Collections.Generic;

using G=Gtk;

using Mono.Addins;

using Galaxium.Core;
using Anculus.Core;

namespace Galaxium.Gui.GtkGui
{
	[ExtensionNode ("MenuItem")]
	public class MenuItemExtension : MenuExtension
	{
		[NodeAttribute]
		string label;
		
		[NodeAttribute]
		string icon;
		
		[NodeAttribute]
		string event_handler;
		
		[NodeAttribute]
		string accel_key;
		
		G.MenuItem _menuItem;
		
		//TODO: I really don't like this... Is there some better way?
		static Dictionary<G.MenuItem, MenuItemExtension> _extensions = new Dictionary<G.MenuItem, MenuItemExtension>();
		
		public static Dictionary<G.MenuItem, MenuItemExtension> Extensions
		{
			get { return _extensions; }
		}
		
		public override G.MenuItem GetMenuItem (G.MenuItem item)
		{
			if (icon != null)
			{
				_menuItem = new G.ImageMenuItem (label);
				G.ImageMenuItem imageItem = (G.ImageMenuItem)_menuItem;
				imageItem.Image = new G.Image(IconUtility.GetIcon (icon, IconSizes.Small));
			}
			else
				_menuItem = new G.MenuItem (label);
			
			if(accel_key != null && accel_key != String.Empty)
			{
				_menuItem.AddAccelerator("activate", MenuUtility.GetAccelGroup (Window), GtkUtility.ParseAccelKey (accel_key));
			}
			
			_menuItem.Visible = true;

			if(event_handler != null && event_handler != String.Empty)
			{
				AbstractMenuCommand command = Addin.CreateInstance (event_handler, false) as AbstractMenuCommand;
				
				if (command != null)
				{
					if(Context != null)
						command.Context = Context;
					
					command.MenuItem = _menuItem;
					_menuItem.Activated += delegate {
						command.Run();
					};
				}
				else
				{
					Log.Error ("Could not find event handler '{0}'", event_handler);
				}
			}
			
			_extensions.Add(_menuItem, this);
			
			return _menuItem;
		}
	}
}